package com.jiayi.weiphoto.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;

public class NetStateTool {
	
	public static boolean isNetWorkingEnable(Context context){
		ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
		for (NetworkInfo networkInfo : networkInfos) {
			if(networkInfo.isAvailable() && networkInfo.getState().equals(NetworkInfo.State.CONNECTED)){
//				MyLog.d("Tool network type is "+networkInfo.getTypeName());
				return true;
			}
		}
		return false;
	}
	
	public static String getNetWorkType(Context context){
		ConnectivityManager conm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo nInfo = conm.getActiveNetworkInfo();
		if(nInfo != null){
			String typeName = nInfo.getTypeName();
			if(typeName != null && typeName.toLowerCase().equals("mobile")){
				typeName = conm.getActiveNetworkInfo().getExtraInfo();
			}
			return typeName.toLowerCase();
		}
		return "unknown";
		/**
		State state_mobile = conm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		State state_wifi = conm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if(State.CONNECTED == state_mobile){
			return "MOBILE";
		}else if(State.CONNECTED==state_wifi){
			return "WIFI";
		}
		return "OTHER";
		**/
		
	}
	
	private String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return null;
	}
}
